package db;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import setting.DbConfig;

public class DBConnection {

	private Connection conn = null;
	private Statement statement = null;
	private ResultSet resultSet = null;

	public DBConnection() {
		try {
			this.conn = DriverManager.getConnection("jdbc:mysql://"
					+ DbConfig.host + "/" + DbConfig.database + "?" + "user="
					+ DbConfig.username + "&password=" + DbConfig.password);
		} catch (SQLException e) {
			System.out.println("Error: Can not connect to Mysql !!!");
			System.exit(-1);
		}
	}

	public void batchQuery(ArrayList<String> batch) {

		try {

			statement = conn.createStatement();

			for (int i = 0; i < batch.size(); i++) {
				statement.addBatch(batch.get(i));
				
			}

			statement.executeBatch();
			statement.clearBatch();
			

		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Unknown Error with Create Statement");
			System.exit(-1);
		}

	}

	public void runQuery(String query) {
		try {

			statement = conn.createStatement();

			statement.executeUpdate(query);
			

		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Unknown Error with Create Statement");
			System.exit(-1);
		}

	}

	public ResultSet select(String query) {
		try {
			if (statement == null) {
				statement = conn.createStatement();
			}
			resultSet = statement.executeQuery(query);

		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Error on Database");
			System.exit(-1);
		}

		return resultSet;

	}

	public boolean tableExist(String tablename) {
		DatabaseMetaData dbm;
		try {
			dbm = conn.getMetaData();
			// check if "employee" table is there
			ResultSet tables;

			tables = dbm.getTables(null, null, tablename, null);

			if (tables.next()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e1) {
			System.out.println("Unknown SQL Error");
			System.exit(-1);
			return false;
		}

	}

}
